<template>
  <div v-loading="loading">
    <div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="dataForm"
        size="medium"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('配置表名')" prop="tableName">
              <el-input
                v-model="form.tableName"
                :placeholder="$t('表名')"
                show-word-limit
                maxlength="64"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('配置表描述')" prop="tableTxt">
              <el-input v-model="form.tableTxt" :placeholder="$t('表描述')" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item :label="$t('配置表类型 ')" prop="tableType">
              <el-select
                v-model="form.tableType"
                :placeholder="$t('表类型')"
                @change="changeTableTable"
              >
                <el-option
                  v-for="item in tableTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
              <el-row style="margin-top: 5px">
                <template v-if="showRelationType">
                  <el-col :span="8">
                    <el-radio-group v-model="form.relationType">
                      <el-radio label="2">一对多</el-radio>
                      <el-radio label="1">一对一</el-radio>
                    </el-radio-group>
                  </el-col>
                  <!-- <el-col :span="2">
                    <span>条件：</span>
                  </el-col> -->
                  <!-- <el-col :span="6">
                    <el-input
                      v-model="form.hideCondition"
                      :placeholder="$t('条件')"
                    />
                  </el-col> -->
                  <el-col :span="2" :offset="6">
                    <span>序号：</span>
                  </el-col>
                  <el-col :span="8">
                    <el-input-number
                      v-model="form.tabOrderNum"
                      :min="1"
                      :max="100"
                      label="序号"
                      placeholder="序号"
                      controls-position="right"
                    />
                  </el-col>
                </template>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('表单类型')" prop="formCategory">
              <el-select
                v-model="form.formCategory"
                placeholder="请选择"
                @change="formCategoryLimit(form.formCategory)"
              >
                <el-option
                  v-for="item in formCategoryOptions"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="processKey">
              <span slot="label">
                <i
                  v-if="
                    form.formCategory === 'act_from' ||
                      form.formCategory === 'deal_act_form' ||
                      form.formCategory === 'fund_act_form' ||
                      form.formCategory === 'lp_act_form'
                  "
                  style="color: #ff4949; margin-right: 4px"
                >*</i>
                {{ $t('流程配置') }}
                <el-tooltip placement="top">
                  <div slot="content">选择流程类型表单时启用 </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-select
                v-model="form.processKey"
                filterable
                :placeholder="$t('请选择')"
                :disabled="isDisabled"
                clearable
              >
                <el-option
                  v-for="process in procDefKeyOptions"
                  :key="process.key"
                  :label="$t(process.name)"
                  :value="process.key"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="扩展选项">
              <el-button
                type="text"
                icon="el-icon-guide"
                @click="detailsConfig(form)"
              >{{ $t("配置") }}</el-button>
              <el-button
                type="text"
                icon="el-icon-ship"
                @click="qutoeConfig()"
              >{{
                $t("引用数据")
              }}</el-button>
            </el-form-item>
          </el-col>
          <el-col v-show="showSubTbale" :span="8">
            <el-form-item :label="$t('子表信息')">
              <el-input v-model="form.subTableStr" readonly>
                <el-button
                  slot="append"
                  icon="el-icon-c-scale-to-original"
                  @click="unfoldSubTable()"
                />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-tabs v-model="activeName" class="formTable">
          <el-tab-pane label="字段属性" name="1">
            <db-property
              v-if="lazyFlag"
              ref="dbTables"
              :data="OnlCgformField"
              :translation="translation"
            />
          </el-tab-pane>
          <el-tab-pane label="页面属性" name="2">
            <pageProperty
              v-if="lazyFlag"
              ref="pageTables"
              :rele="form.formCategory"
            />
          </el-tab-pane>
          <el-tab-pane label="校验字段" name="3">
            <verifyProperty v-if="lazyFlag" ref="verifyTables" />
          </el-tab-pane>
          <el-tab-pane label="查询配置" name="5">
            <queryProperty v-if="lazyFlag" ref="queryProperty" />
          </el-tab-pane>
          <el-tab-pane v-if="showRelationType" label="关联配置" name="4">
            <foreignProperty v-if="lazyFlag" ref="foreignProperty" />
          </el-tab-pane>
          <el-tab-pane v-if="possessHeadShare" label="事件处理" name="10">
            <eventProperty v-if="lazyFlag" ref="eventProperty" />
          </el-tab-pane>
          <el-tab-pane v-if="possessHeadShare" label="表单事件" name="11">
            <onlFormEventDispose v-if="lazyFlag" ref="onlFormEventDispose" />
          </el-tab-pane>
          <el-tab-pane v-if="possessHeadShare" label="按钮配置" name="6" />
          <el-tab-pane v-if="possessHeadShare" label="代码配置" name="7" />
          <el-tab-pane v-if="possessHeadShare" label="SQL配置" name="8" />
          <el-tab-pane v-if="viewConfigShow" label="视图配置" name="9" />
        </el-tabs>
        <div v-if="activeName === '6'">
          <buttonProperty ref="buttonProperty" />
        </div>
        <div v-if="activeName === '7'">
          <onlCgformEnhanceJavaList ref="onlCgformEnhanceJavaList" />
        </div>
        <div v-if="activeName === '8'">
          <onlCgformEnhanceSqlList ref="onlCgformEnhanceSqlList" />
        </div>
        <div v-if="activeName === '9'">
          <onl-view-form ref="onlViewForm" />
        </div>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <!--保存 取消按钮-->
      <save-btn has-permi="system:head" />
    </div>
    <el-dialog
      :title="$t('扩展配置')"
      :visible.sync="detailsOpen"
      width="50%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <el-form
        ref="form"
        class="dataForm"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('表单布局')">
              <el-select v-model="form.formTemplate" placeholder="请选择">
                <el-option
                  v-for="item in gridOption"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('是否分页 ')">
              <el-select v-model="form.isPage" placeholder="请选择">
                <el-option
                  v-for="item in pagingOption"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('表单风格')">
              <el-select v-model="form.formStyle" placeholder="请选择">
                <el-option
                  v-for="item in formStyleOption"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('附件上传')">
              <el-select v-model="form.isFileUpload" placeholder="请选择">
                <el-option
                  v-for="item in pagingOption"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('附件类型')">
              <span slot="label">
                {{ $t("附件类型") }}
                <el-tooltip
                  :content="
                    $t(
                      '关联页面类型，附件根据该字段分文件夹存储.默认为:online_form'
                    )
                  "
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-input
                v-model="form.fileDataType"
                :placeholder="$t('附件类型')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('附件业务类型')">
              <span slot="label">
                {{ $t("附件业务类型") }}
                <el-tooltip
                  :content="
                    $t(
                      '附件根据该字段显示对应文件夹${}格式为从url中取值，FileTable组件中business-type参数，默认为空'
                    )
                  "
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-input
                v-model.trim="form.fileBusinessType"
                :placeholder="$t('附件业务类型')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('附件是否显示业务数据')">
              <span slot="label">
                {{ $t("附件是否显示业务数据") }}
                <el-tooltip
                  :content="
                    $t(
                      '附件根据该字段判断是否显示业务数据，FileTable组件中select-business-data参数，默认为空'
                    )
                  "
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-select v-model="form.fileIsBusinessData" placeholder="请选择" clearable>
                <el-option
                  v-for="item in ifTypeOption"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('选填附件')" prop="optionalFile">
              <treeselect
                v-model="form.optionalFileList"
                :options="defaultDir"
                :flat="true"
                :multiple="true"
                :placeholder="$t('表单选填附件')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('开启通知')">
              <span slot="label">
                {{ $t("开启通知") }}
                <el-tooltip
                  :content=" $t('开启通知后需要选择模板') "
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-switch
                v-model="form.enableNotice"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="Y"
                inactive-value="N"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('选择模板')">
              <span slot="label">
                {{ $t("选择模板") }}
                <el-tooltip
                  :content=" $t('模板配置:系统管理->通知公告->通知类型') "
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-select v-model="form.noticeTemplate" placeholder="请选择" :disabled="form.enableNotice=='N'">
                <el-option
                  v-for="item in templateOption"
                  :key="item.noticeCode"
                  :label="item.noticeType"
                  :value="item.noticeCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒类型')">
              <el-select v-model="form.noticeType" placeholder="请选择" :disabled="form.enableNotice=='N'">
                <el-option
                  v-for="item in noticeTypeOption"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒对象')">
              <user-select v-if="form.noticeType === 'sys_user'" v-model="form.noticeObjectIds" :placeholder="$t('请选择')" multiple :disabled="form.enableNotice=='N'" />
              <el-select v-else v-model="form.noticeObjectIds" filterable multiple :placeholder="$t('请选择')" :disabled="form.enableNotice=='N'">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('流程标题')">
              <span slot="label">
                {{ $t("流程标题") }}
                <el-tooltip
                  :content="
                    $t(
                      '格式：${ }, 括号内支持三种格式数据： 1.项目名称/基金名称/公司名称， 2.字段名称， 3.当前日期：new Date。例：${项目名称}-${name}-${new Date}'
                    )
                  "
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-input
                v-model="form.processActTitle"
                :placeholder="$t('流程标题')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('代码生成包路径')">
              <el-input
                v-model="form.packetPath"
                :placeholder="$t('代码生成包路径')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <!--保存 取消按钮-->
        <el-button @click="detailsOpen = false">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="引用数据"
      :visible.sync="quoteOpen"
      width="50%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <el-form
        ref="form"
        class="dataForm"
        :model="quoteForm"
        :rules="rules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('用途')">
              <el-select v-model="quoteForm.effect" placeholder="请选择" disabled>
                <el-option
                  v-for="item in effectOption"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('引用表名')">
              <el-select
                v-model="quoteForm.table"
                placeholder="请选择"
                filterable
                @change="getFieldName(quoteForm.table)"
              >
                <el-option
                  v-for="item in tableNameOption"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('源字段')">
              <el-select v-model="quoteForm.sField" placeholder="字段">
                <el-option
                  v-for="item in sourceFieldsOption"
                  :key="item.id"
                  :label="item.dbFieldTxt"
                  :value="item.dbFieldName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('链接字段')">
              <el-select v-model="quoteForm.lField" placeholder="字段">
                <el-option
                  v-for="item in linkFieldsOption"
                  :key="item.id"
                  :label="item.dbFieldTxt"
                  :value="item.dbFieldName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="area-header">
          <span class="area-header-title">字段映射</span>
        </div>
        <el-table
          :data="quoteForm.mappings"
          tooltip-effect="dark"
          max-height="400"
          border
        >
          <el-table-column label="源字段" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.sourceField" placeholder="字段">
                <el-option
                  v-for="item in sourceFieldsOption"
                  :key="item.id"
                  :label="item.dbFieldTxt"
                  :value="item.dbFieldName"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="映射字段" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.linkField" placeholder="字段">
                <el-option
                  v-for="item in linkFieldsOption"
                  :key="item.id"
                  :label="item.dbFieldTxt"
                  :value="item.dbFieldName"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" width="80" label="操作">
            <template slot-scope="scope">
              <el-button
                type="danger"
                plain
                size="mini"
                circle
                icon="el-icon-minus"
                @click="minusHandle(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="addHandle()"
          >新增</el-button>
        </div>

      </el-form>
      <div slot="footer">
        <el-button @click="closeQupte()">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="子表信息"
      :visible.sync="subDialogVisible"
      width="70%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <subTableList ref="subTableList" :sub-table="form" />
    </el-dialog>
  </div>
</template>

<script>
import { delDbField, getDirByBelong } from '@/api/system/desform/onlineForm/onlCgformHead'
import { saveAll, delDbDetails, getRequest, findMsgTemplate } from '@/api/system/desform/onlineForm/onlCgformHead'
import { listDataProcess } from '@/api/act/process/actProcess'
import dbProperty from '@/components/desform/dbProperty'
import pageProperty from '@/components/desform/pageProperty'
import verifyProperty from '@/components/desform/verifyProperty'
import foreignProperty from '@/components/desform/foreignProperty'
import buttonProperty from '@/components/desform/buttonProperty'
import queryProperty from '@/components/desform/queryProperty'
import eventProperty from '@/components/desform/eventProperty'
import onlFormEventDispose from '@/components/desform/onlFormEventDispose'
import subTableList from '@/components/desform/head/subTableList'
import onlCgformEnhanceJavaList from '../enhance/onlCgformEnhanceJavaList.vue'
import onlCgformEnhanceSqlList from '../enhance/onlCgformEnhanceSqlList.vue'
import { allRole } from '@/api/system/role'

import { mapActions, mapState } from 'vuex'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getFieldListByHeadId } from '@/api/system/desform/data/onlCgformHeadBtn'
import onlViewForm from '@/views/system/desform/enhance/onlViewForm.vue'
import { getConfigKey } from '@/api/system/config'
   const gridOption = [
    { title: '一列', value: '24' },
    { title: '两列', value: '12' },
    { title: '三列', value: '8' },
    { title: '四列', value: '6' }
  ]
    const pagingOption = [
    { title: '是', value: '1' },
    { title: '否', value: '0' }

  ]
  const businessTypeOption = [
    { title: '项目', value: 'deal' },
    { title: '基金', value: 'fund' }
  ]
  // 表单分类
  const formCategory = [
    { title: '默认表单(无流程)', value: 'norm_form' },
    { title: '项目表单(无流程)', value: 'deal_form' },
    { title: '基金表单(无流程)', value: 'fund_form' },
    { title: '出资人表单(无流程)', value: 'lp_form' },
    { title: '流程表单', value: 'act_from' },
    { title: '项目_流程表单', value: 'deal_act_form' },
    { title: '基金_流程表单', value: 'fund_act_form' },
    { title: '出资人_流程表单', value: 'lp_act_form' }
  ]
    const formStyle = [
      { title: '默认风格(表格+表单)', value: 'norm_style' },
      { title: '表单风格(表单)', value: 'form_style' },
      { title: '视图风格(视图列表)', value: 'view_style' }
    ]
    const noticeTypeOption = [
      { title: '系统用户', value: 'sys_user' },
      { title: '系统角色', value: 'sys_role' }
    ]
    const effectOption = [{
    title: '新增',
    value: 'add'
  },
  {
    title: '查看',
    value: 'see'
  }
]
    export default {
      components: {
        dbProperty,
        pageProperty,
        verifyProperty,
        foreignProperty,
        queryProperty,
        Treeselect,
        subTableList,
        buttonProperty,
        eventProperty,
        onlFormEventDispose,
        onlCgformEnhanceJavaList,
        onlCgformEnhanceSqlList,
        onlViewForm
      },
        data() {
          // 验证表明
         var validateTableName = (rule, value, callback) => {
        if (!value) {
           return callback(new Error('表名不能为空'))
        } else {
          var patt1 = new RegExp('^[a-zA-Z]{1}_.*')
          var patt2 = /[`~!@#$%^&*()\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im
          if (patt1.test(value)) {
            callback(new Error('不能以单个字母加下划线开头'))
          } else if (patt2.test(value)) {
            callback(new Error('不能含有特殊符号'))
          } else if (new RegExp('^[0-9]*$').test(value)) {
            callback(new Error('不能全部是数字'))
          } else if (/[\u4E00-\u9FA5]/g.test(value)) {
            callback(new Error('不能输入汉字'))
          } else {
            var params = {
              id: !this.headId ? '' : this.headId,
              tbname: value
            }
            getRequest(this.checkUrl.checkOnlyTable, params).then(res => {
              if (res.data) {
                if (res.data === -1) {
                  callback(new Error('表名已存在！'))
                }
              }
              callback()
            })
          }
        }
      }
          // 验证流程配置
          var isRequiredProcessKey = (rule, value, callback) => {
            var formCategory = this.form.formCategory
           if (!value && (formCategory.includes('act_from'))) {
             return callback(new Error('流程配置不能为空'))
           } else {
             callback()
           }
          }
            return {
               // 表信息id
               headId: '',
               // 映射关系
               showRelationType: false,
                // 流程下拉框
               procDefKeyOptions: [],
               subDialogVisible: false,
               subTableData: [],
               quoteForm: {},
               effectOption: effectOption,
               tableNameOption: [],
               linkFieldsOption: [],
               warpData: {},
               showSubTbale: false,
               quoteOpen: false,
                // 调用接口类型
                url: '',
                 checkUrl: {
                 checkOnlyTable: '/head/onlCgformHead/api/checkOnlyTable'
                },
                // 延迟加载组件
                lazyFlag: false,
                gridOption: gridOption,
                pagingOption: pagingOption,
                businessTypeOption: businessTypeOption,
                formStyleOption: formStyle,
                // 表单参数
                form: {},
                OnlCgformField: [],
                mainActiveName: 'first',
                activeName: '1',
                tableTypeOptions: [{ value: 1, label: '单表' }, { value: 2, label: '主表' }, { value: 3, label: '子表' }],
                // 表单分类字典
                formCategoryOptions: formCategory,
                // 流程配置是否只读
                isDisabled: true,
                // 遮罩层
                loading: false,
                sql: '',
                // 详情配置
                detailsOpen: false,
                // 附件文件树状图
                defaultDir: [],
                possessHeadShare: false,
                // 是否展示视图配置
                viewConfigShow: false,
                templateOption: [], // 通知类型模板
                noticeTypeOption: noticeTypeOption,
                roleOptions: [],
                // 是否选项
                ifTypeOption: [{ title: '是', value: '0' }, { title: '否', value: '1' }],
                // 表单校验
                rules: {
                tableName: [
                    { validator: validateTableName, trigger: 'blur' },
                     { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                 tableType: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                tableTxt: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                  formCategory: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  processKey: [
                    { validator: isRequiredProcessKey, trigger: 'blur' }
                  ]
                },
              // 备注翻译字段名方式  拼音/英文
              translation: undefined
            }
        },
         computed: {
         ...mapState('dbAbout', ['dbPropertyList', 'head']),
          sourceFieldsOption() {
              return this.dbPropertyList
        }
         },
        created() {
           // 查询流程下拉框
          listDataProcess().then(response => {
            this.procDefKeyOptions = response.data
          })
          // 选填附件内容
          this.getDefaultDir()
          this.getFieldList()
          findMsgTemplate().then(response => {
                this.templateOption = response.data
            })
          allRole().then(response => {
          this.roleOptions = response.data
        })
          getConfigKey('onl_cgform_translation').then((res) => {
            if (res.code === 200) {
              this.translation = res.msg
            }
          })
        },
        mounted() {
        },
        methods: {
           ...mapActions('dbAbout', ['initDbProperty', 'addDbProperty', 'delDbProperty', 'resetArray', 'dbPropertyList', 'possessHead']),
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    this.$nextTick(() => {
                    delDbDetails(data.id).then(response => {
                        this.form = response.data.head
                        if (response.data.head.relationType != null) {
                        this.form.relationType = response.data.head.relationType.toString()
                        }
                        this.showSubTbale = !(response.data.head.subTableStr == null || response.data.head.subTableStr === '')
                        this.showRelationType = (response.data.head.tableType === 3)
                        this.initDbProperty(response.data.fields)
                        this.possessHead(response.data.head) // 共享表头信息
                        this.url = '/head/onlCgformHead/api/editAll'
                        this.lazyFlag = true
                        this.loading = false
                        this.headId = data.id
                        var formCategory = this.form.formCategory
                        if (formCategory.includes('act_from') || formCategory.includes('act_form')) {
                          this.isDisabled = false
                        } else {
                          this.isDisabled = true
                        }
                        this.activeName = '1'
                        this.possessHeadShare = true
                        this.viewConfigShow = this.form.formStyle === 'view_style'
                        if (this.form.quoteContent) {
                              this.quoteForm = JSON.parse(this.form.quoteContent)
                              console.log('this.quoteForm.table', this.quoteForm.table)
                              this.getFieldName(this.quoteForm.table)
                        }
                        this.$nextTick(() => {
                          this.$refs.pageTables.getGroupFields(data.id)
                        })
                  })
                   })
                } else {
                    this.url = '/head/onlCgformHead/api/addAll'
                    this.reset()
                    this.possessHead({}) // 共享表头信息
                    this.initDbProperty([])
                    this.lazyFlag = true
                    this.loading = false
                    this.showSubTbale = false
                    this.showRelationType = false
                    this.headId = ''
                    this.isDisabled = true
                    this.activeName = '1'
                    this.possessHeadShare = false
                    this.form.quoteContent = ''
                    this.quoteForm = {
                            mappings: []
                    }
                }
            },
            // 表单重置
            reset() {
                this.form = {
                  formCategory: 'norm_form',
                  isFileUpload: '0',
                  formTemplate: '12',
                  isPage: '1',
                  relationType: '1',
                  processKey: undefined,
                  formStyle: 'norm_style',
                  tableType: 1,
                  fileDataType: 'online_form',
                  fileBusinessType: undefined,
                  fileIsBusinessData: undefined,
                  noticeType: 'sys_user',
                  enableNotice: 'N',
                  noticeObjectIds: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        this.classifyIntoFormData()
                        console.log('this.form', this.form)
                        // 单独保存视图
                        if (this.$refs.onlViewForm) {
                          this.$refs.onlViewForm.submitForm()
                        }
                        // 如果有分组字段列表
                        if (this.$refs.pageTables.groupFields) {
                          console.log(this.$refs.pageTables.groupFields)
                          this.form.groupFields = this.$refs.pageTables.groupFields
                        }
                        if (this.form.fields) {
                          this.form.fields.forEach(item => {
                            if (item.dbIsNull === true) {
                              item.dbIsNull = 1
                            }
                            if (item.dbIsNull === false) {
                              item.dbIsNull = 0
                            }
                          })
                        }
                        console.log(this.form.fields, 'this.form.fields')
                        saveAll(this.url, this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                        })
                         this.loading = false
                    } else {
                       this.locationError(document)
                    }
                })
           },
            // 将数据整理成对象
            classifyIntoFormData() {
              const formData = { head: {}, fields: [], indexs: [] }
              formData.head = Object.assign({}, this.form)
              const tables1 = this.$refs.dbTables.tableData
              const tables2 = this.$refs.pageTables.tableData
              const tables3 = this.$refs.verifyTables.tableData
              const tables5 = this.$refs.queryProperty.tableData
              const tables4 = this.showRelationType ? this.$refs.foreignProperty.tableData : []
              // 组装提交的对象
              tables1.forEach((element, index) => {
                element.orderNum = index
                const field = {
                  ...tables2[index],
                  ...tables3[index],
                  ...tables4[index],
                  ...tables5[index],
                  ...element,
                  isReadOnly: tables2[index].isReadOnly ? 1 : 0,
                  isShowForm: tables2[index].isShowForm ? 1 : 0,
                  isShowList: tables2[index].isShowList ? 1 : 0,
                  fieldMustInput: tables3[index].fieldMustInput ? 1 : 0,
                  isQuery: tables5[index].isQuery ? 1 : 0
                }
                if (element.id) {
                  field.id = element.id
                } else {
                  delete field.id
                }
                formData.fields.push(field)
              })

              this.form = formData
            },
           // 表类型改变事件
          changeTableTable(data) {
              if (data === 3) {
                this.showRelationType = true
                // 默认关系为一对多
                this.form.relationType = '2'
              } else {
                this.showRelationType = false
                this.activeName = '1'
              }
            },
          // 表单配置删除数据
          delFormCategory(dealId, fundId, lpId, actStatus, actId, actTitle) {
           var delList = []
            this.dbPropertyList.forEach(e => {
              if (e.dbFieldName === dealId || e.dbFieldName === fundId || e.dbFieldName === lpId || e.dbFieldName === actStatus || e.dbFieldName === actId || e.dbFieldName === actTitle) {
                delList.push(e)
              }
            })
            this.delDbProperty(delList)
            // 删除有id的列数据
            delList.map(e => {
              if (e.id) {
                delDbField(e.id)
              }
            })
          },
          // 表单配置点击事件
          formCategoryLimit(val) {
                const deal = {
                  dbFieldName: 'deal_id',
                  dbLength: '64',
                  dbPointLength: '0',
                  dbDefaultVal: '',
                  dbFieldTxt: '关联字段',
                  dbIsNull: true,
                  dbType: 'string',
                  index: 0
                }
                const fund = {
                  dbFieldName: 'fund_id',
                  dbLength: '64',
                  dbPointLength: '0',
                  dbDefaultVal: '',
                  dbFieldTxt: '关联字段',
                  dbIsNull: true,
                  dbType: 'string',
                  index: 0
                }
                const lp = {
                  dbFieldName: 'lp_id',
                  dbLength: '64',
                  dbPointLength: '0',
                  dbDefaultVal: '',
                  dbFieldTxt: '关联字段',
                  dbIsNull: true,
                  dbType: 'string',
                  index: 0
                }
                const actStatus = {
                  dbFieldName: 'act_status',
                  dbLength: '2',
                  dbPointLength: '0',
                  dbDefaultVal: '',
                  dbFieldTxt: '流程状态',
                  dbIsNull: true,
                  dbType: 'string',
                  index: 0
                }
                const actId = {
                  dbFieldName: 'act_id',
                  dbLength: '64',
                  dbPointLength: '0',
                  dbDefaultVal: '',
                  dbFieldTxt: '流程Id',
                  dbIsNull: true,
                  dbType: 'string',
                  index: 0
                }
                const actTitle = {
                  dbFieldName: 'act_title',
                  dbLength: '100',
                  dbPointLength: '0',
                  dbDefaultVal: '',
                  dbFieldTxt: '流程标题',
                  dbIsNull: true,
                  dbType: 'string',
                  index: 0
                }
                let disabled = true
                const categories = ['deal_id', 'fund_id', 'lp_id', 'act_status', 'act_id', 'act_title']
                let toAdd = []
                switch (val) {
                  case 'norm_form':
                    categories.forEach(category => this.delFormCategory(category))
                    break
                  case 'deal_form':
                    this.delFormCategory('fund_id', 'lp_id', 'act_status', 'act_id', 'act_title')
                    categories.splice(0, 1)
                    toAdd.push(deal)
                    break
                  case 'fund_form':
                    this.delFormCategory('deal_id', 'lp_id', 'act_status', 'act_id', 'act_title')
                    categories.splice(1, 1)
                    toAdd.push(fund)
                    break
                  case 'lp_form':
                    this.delFormCategory('deal_id', 'fund_id', 'act_status', 'act_id', 'act_title')
                    categories.splice(2, 1)
                    toAdd.push(lp)
                    break
                  case 'act_from':
                    disabled = false
                    this.delFormCategory('deal_id', 'fund_id', 'lp_id')
                    categories.splice(0, 3)
                    toAdd = [actStatus, actTitle, actId]
                    break
                  case 'deal_act_form':
                    disabled = false
                    this.delFormCategory('fund_id', 'lp_id')
                    categories.splice(1, 2)
                    toAdd = [deal, actStatus, actTitle, actId]
                    break
                  case 'fund_act_form':
                    disabled = false
                    this.delFormCategory('deal_id', 'lp_id')
                    categories.splice(0, 1)
                    categories.splice(1, 1)
                    toAdd = [fund, actStatus, actTitle, actId]
                    break
                  case 'lp_act_form':
                    disabled = false
                    this.delFormCategory('deal_id', 'fund_id')
                    categories.splice(0, 2)
                    toAdd = [lp, actStatus, actTitle, actId]
                    break
                }
                this.isDisabled = disabled
                this.form.processKey = undefined
                toAdd.forEach(item => {
                  const existing = this.dbPropertyList.find(prop => prop.dbFieldName === item.dbFieldName)
                  if (!existing) {
                    this.addDbProperty(item)
                  }
                })
          },
          // 详情配置弹出层
          detailsConfig(form) {
              this.detailsOpen = true
              console.log(form)
          },
          // 获取选填附件内容
          getDefaultDir() {
            getDirByBelong().then(res => {
              res.data.forEach(item => {
                this.checkFileNormalizer(item)
              })
              this.defaultDir = res.data
            })
          },
          // 设置选填附件多选 value/label
          checkFileNormalizer(item) {
            if (item.children && item.children.length === 0) {
              delete item.children
            }
            return {
              id: item.id,
              label: item.name,
              children: item.children
            }
          },
          unfoldSubTable() { // 子表列表
            this.subDialogVisible = true
          },
          removeSubTableStr(str) {
                 if (str == null || str === '') {
                  this.showSubTbale = false
                  this.subDialogVisible = false
                 }
                this.form.subTableStr = str
          },
          qutoeConfig() {
              this.quoteOpen = true
          },
          closeQupte() {
            this.form.quoteContent = JSON.stringify(this.quoteForm)
            this.quoteOpen = false
          },
           getFieldList() {
              getFieldListByHeadId().then(res => {
                this.warpData = res.data
                Object.keys(this.warpData).map((key) => {
                  this.tableNameOption.push(key)
                })
              })
            },
            getFieldName(tbname) {
              this.linkFieldsOption = this.warpData[tbname]
            },
            addHandle() {
                  const obj = {
                    sourceField: undefined,
                    linkField: undefined
                  }
                // 不是数组置为空数组
                if (!(this.quoteForm.mappings instanceof Array)) {
                      this.quoteForm.mappings = []
                  }
                  this.quoteForm.mappings.push(obj)
                  this.$forceUpdate()
            },
            minusHandle(index) {
              this.quoteForm.mappings.splice(index, 1)
            }
        }
    }
</script>
<style scoped>
.dialog-footer {
  padding: 10px 16px;
  /* text-align: right;
  background-color: #fff; */
  border-radius: 0 0 4px 4px;
  bottom: 0px;
  right: 0px;
  position: fixed;
}
</style>
